import 'dart:async';
import 'package:flutter/material.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/models/book/BookSearchDto.dart';
import 'package:ichinesereader/models/book/BookFilters.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:ichinesereader/models/common/SelectOption.dart';
import 'package:ichinesereader/utils/log.dart';
import '../../themes/appTheme.dart';

class AppKeys {
  static List<GlobalKey<FormFieldState>> searchFormKeys = [
    GlobalKey<FormFieldState>(),
    GlobalKey<FormFieldState>(),
    GlobalKey<FormFieldState>(),
    GlobalKey<FormFieldState>(),
    GlobalKey<FormFieldState>(),
    GlobalKey<FormFieldState>(),
  ];
}

class IBAppKeys {
  static List<GlobalKey<FormFieldState>> searchIBFormKeys = [
    GlobalKey<FormFieldState>(),
    GlobalKey<FormFieldState>(),
    GlobalKey<FormFieldState>(),
    GlobalKey<FormFieldState>(),
    GlobalKey<FormFieldState>(),
  ];
}

// ignore: must_be_immutable
class SearchDialog extends StatefulWidget {
  SearchDialog({
    Key? key,
    required this.readingType,
    required this.title,
    required this.selected,
    required this.message,
    required this.readingTypeFrom,
  }) : super(key: key);

  String title;
  final List<String> selected;
  String message;
  NanhaiBookReadingTypes readingType;
  String readingTypeFrom;

  _SearchDialogState createState() => new _SearchDialogState();
}

class _SearchDialogState extends State<SearchDialog> {
  final programTypeKey = GlobalKey<FormFieldState>();
  final ibTypeKey = GlobalKey<FormFieldState>();
  final BooksController _booksController = Get.find();

  //late BookFilter chidrenOptions;
  String index = 'Immersion';
  String? ibindex = '';
  String searchText = '';
  String? query;
  List<String> programs = [];
  late BookSearchDto dto;
  List<SelectOption> options = Constants.textSearchOptions;
  late BookFilter filterIBChinese;

  @override
  void initState() {
    super.initState();
    //dto = new BookSearchDto();
    dto = _booksController.getBookSearchDeto();
    if (dto.programType?[0] == 'AP Chinese') {
      index = 'AP Chinese';
    }
    if (dto.programType?[0] == 'IB Chinese') {
      index = 'IB Chinese';
      if (dto.textType?[0] != null) {
        ibindex = dto.textType?[0];
      }
    }
    if (dto.query != null) {
      query = dto.query;
    } else {
      query = '';
    }
  }

  late TextEditingController textController =
      TextEditingController(text: query);

  void clearText() {
    // paginationKey.currentState?.currentPage = 1;
    textController.clear();
    dto.query = null;
    _booksController.setBookSearchDto(dto);
    if (widget.readingTypeFrom == "library") {
      _booksController.fetchSearchOpenLibraryBookItems(20, 0, dto);
    } else {
      _booksController.fetchSearchProgressreadingBookItems(20, 0, dto);
    }
  }

  void setLang(lang) {
    // paginationKey.currentState?.currentPage = 1;
    dto.language = lang;
    _booksController.setBookSearchDto(dto);
    Log.debug(widget.readingTypeFrom == "library");
    if (widget.readingTypeFrom == "library") {
      _booksController.fetchSearchOpenLibraryBookItems(20, 0, dto);
    } else {
      _booksController.fetchSearchProgressreadingBookItems(20, 0, dto);
    }
  }

  void _handleOptions(value) {
    // paginationKey.currentState?.currentPage = 1;
    setState(() {
      index = value;
      ibindex = '';
    });
    List<String> programs = [];
    programs.add(value);
    dto.programType = programs;
    _booksController.setBookSearchDto(dto);
    Log.debug(widget.readingTypeFrom);
    if (widget.readingTypeFrom == "library") {
      _booksController.fetchSearchOpenLibraryBookItems(20, 0, dto);
    } else {
      _booksController.fetchSearchProgressreadingBookItems(20, 0, dto);
    }
  }

  Timer searchOnStoppedTyping = Timer.periodic(
    const Duration(seconds: 1000),
    (timer) {},
  );

  void _onChangeHandler(value) {
    const duration = Duration(milliseconds: 1000);
    // set the duration that you want call search() after that.
    setState(() => searchOnStoppedTyping.cancel());
    setState(() => searchOnStoppedTyping =
        new Timer(duration, () => _handleSearchText(value)));
  }

  void _handleSearchText(value) {
    // paginationKey.currentState?.currentPage = 1;
    dto.query = value;
    _booksController.setBookSearchDto(dto);
    // Log.debug(widget.readingTypeFrom);
    if (widget.readingTypeFrom == "library") {
      _booksController.fetchSearchOpenLibraryBookItems(20, 0, dto);
    } else {
      _booksController.fetchSearchProgressreadingBookItems(20, 0, dto);
    }
  }

// for IB type type dropdown
  void _handleIBOptions(value) {
    // paginationKey.currentState?.currentPage = 1;
    List<String> programs = [];
    programs.add(value);
    dto.textType = programs;
    _booksController.setBookSearchDto(dto);
    if (widget.readingTypeFrom == "library") {
      _booksController.fetchSearchOpenLibraryBookItems(20, 0, dto);
    } else {
      _booksController.fetchSearchProgressreadingBookItems(20, 0, dto);
    }
    setState(() {
      ibindex = value;
    });
  }

  void _handleSubOptions(label, value) {
    // paginationKey.currentState?.currentPage = 1;
    List<String> programs = [];
    if (label == 'Proficiency Level') {
      programs.add(value.replaceAll(' ', ''));
      dto.proficiencyLevel = programs;
    } else if (label == 'Interest Level') {
      programs.add(value);
      dto.interestLevel = programs;
    } else if (label == 'Text Type') {
      programs.add(value);
      dto.textType = programs;
    } else if (label == 'Topics') {
      programs.add(value);
      dto.topics = programs;
    } else if (label == 'Series') {
      programs.add(value);
      dto.seriesId = programs;
    } else if (label == 'Benchmark') {
      if (value == true) {
        programs.add('true');
      } else {
        programs.add('false');
      }
      dto.teacherAssessment = value;
    }
    _booksController.setBookSearchDto(dto);
    if (widget.readingTypeFrom == "library") {
      _booksController.fetchSearchOpenLibraryBookItems(20, 0, dto);
    } else {
      _booksController.fetchSearchProgressreadingBookItems(20, 0, dto);
    }
  }

// for IB type type dropdown
  void _handleSubIBOptions(label, value) {
    // paginationKey.currentState?.currentPage = 1;
    List<String> programs = [];
    if (label == 'Proficiency Level') {
      programs.add(value.replaceAll(' ', ''));
      // there is a bug
      dto.proficiencyLevel = programs;
    } else if (label == 'My Grade') {
      programs.add(value);
      dto.interestLevel = programs;
    } else if (label == 'Themes') {
      programs.add(value);
      dto.topics = programs;
    } else if (label == 'Mock Exams') {
      programs.add(value);
      dto.seriesId = programs;
    }
    _booksController.setBookSearchDto(dto);
    if (widget.readingTypeFrom == "library") {
      _booksController.fetchSearchOpenLibraryBookItems(20, 0, dto);
    } else {
      _booksController.fetchSearchProgressreadingBookItems(20, 0, dto);
    }
  }

  void initialProgremType() {
    dto.proficiencyLevel = null;
    dto.interestLevel = null;
    dto.textType = null;
    dto.topics = null;
    dto.seriesId = null;
    dto.teacherAssessment = null;
  }

// for IB type type dropdown
  void initialIBProgremType() {
    dto.proficiencyLevel = null;
    dto.interestLevel = null;
    dto.topics = null;
    dto.seriesId = null;
  }

  void clearAll() {
    // //textController.clear();
    // paginationKey.currentState?.currentPage = 1;
    dto = new BookSearchDto();
    _booksController.setBookSearchDto(dto);
    //dto = _booksController.getBookSearchDeto();
    if (widget.readingTypeFrom == "library") {
      _booksController.fetchSearchOpenLibraryBookItems(20, 0, dto);
    } else {
      _booksController.fetchSearchProgressreadingBookItems(20, 0, dto);
    }
    initialProgremType();
    initialIBProgremType();
    for (var i = 0; i < 6; i++) {
      AppKeys.searchFormKeys[i].currentState!.reset();
      //IBAppKeys.searchIBFormKeys[i].currentState!.reset();
    }
    // not work
    for (var i = 0; i < 4; i++) {
      IBAppKeys.searchIBFormKeys[i].currentState!.reset();
    }
    programTypeKey.currentState!.reset();
    ibTypeKey.currentState!.reset();
  }

  @override
  Widget build(BuildContext context) {
    if (_booksController.bookfilters.isEmpty)
      _booksController.getBooksFilters();
    //final box = Hive.box('appconfig');
    // bool isStudent = box.get(CacheManagerKey['nanhairole'].toString()) ==
    //     Constants.NanhaiRole_Student;
    // bool isIndividual = box.get(CacheManagerKey['nanhairole'].toString()) ==
    //     Constants.NanhaiRole_Individual;
    // // double width = MediaQuery.of(context).size.width >= 600
    // //     ? 600
    // //     : MediaQuery.of(context).size.width;
    double width = 400;
    return AlertDialog(
      title: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(widget.title),
          InkWell(
            onTap: () {
              Navigator.of(context).pop();
              clearAll();
            },
            child: Icon(Icons.cancel,
                color: Get.isDarkMode ? Colors.white : Colors.blueGrey),
          ),
        ],
      ),
      titleTextStyle: TextStyle(
          letterSpacing: 1,
          color: Get.isDarkMode ? Get.theme.primaryColorDark : Colors.blueGrey,
          fontSize: 21),
      backgroundColor:
          Get.isDarkMode ? AppTheme.colors.darkTheme2 : Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(
          Radius.circular(6.0),
        ),
      ),
      content: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Expanded(
                      child: Container(
                        width: width,
                        child: Column(
                          children: [
                            //CloseDialog(),
                            TextFormField(
                              style: TextStyle(
                                  color: Get.isDarkMode
                                      ? Colors.white
                                      : Colors.blueGrey),
                              onChanged: (text) {
                                //_handleSearchText(textController.text);
                                _onChangeHandler(textController.text);
                              },
                              controller: textController,
                              decoration: InputDecoration(
                                prefixIcon: Icon(Icons.search),
                                suffixIcon: IconButton(
                                  icon: Icon(
                                    Icons.clear,
                                    size: 15.0,
                                  ),
                                  onPressed: () {
                                    clearText();
                                  },
                                ),
                                hintText: 'Search Books...'.tr,
                                hintStyle: TextStyle(
                                  color: Get.isDarkMode
                                      ? Get.theme.primaryColor
                                      : Colors.grey[300],
                                ),
                                border: OutlineInputBorder(),
                              ),
                            ),
                            Padding(
                              padding:
                                  const EdgeInsets.symmetric(vertical: 12.0),
                              child: FormBuilderField(
                                  name: "language",
                                  initialValue: dto.language ?? 'Mandarin',
                                  builder: (FormFieldState<dynamic> field) {
                                    return InputDecorator(
                                      decoration: InputDecoration(
                                        //labelText: label,
                                        contentPadding: EdgeInsets.all(12.0),
                                        border: InputBorder.none,
                                        errorText: field.errorText,
                                      ),
                                      child: ToggleButtons(
                                        color: Get.isDarkMode
                                            ? Get.theme.primaryColorLight
                                            : Colors.grey,
                                        selectedColor: Get.isDarkMode
                                            ? Colors.black
                                            : AppTheme.colors.lightOrange,
                                        fillColor: Get.isDarkMode
                                            ? Colors.white
                                            : AppTheme.colors.orangeBtn,
                                        children: options.map((option) {
                                          return Container(
                                              padding: EdgeInsets.symmetric(
                                                horizontal: 8,
                                                vertical: 5,
                                              ),
                                              child: Text("${option.label}"));
                                        }).toList(),
                                        onPressed: (int index) {
                                          field.didChange(options[index].value);
                                          setLang(options[index].value);
                                        },
                                        isSelected: options
                                            .map((option) =>
                                                option.value == field.value)
                                            .toList(),
                                      ),
                                    );
                                  }),
                            ),
                            Obx(() {
                              var bookfilters = _booksController.bookfilters;
                              if (_booksController.bookfilters.length > 0) {
                                List<BookFilter> subOptions;
                                List<BookFilter> selected = bookfilters
                                    .where((item) => item.label == index)
                                    .toList();
                                // before choosed
                                if (selected.length == 0) {
                                  subOptions =
                                      _booksController.bookfilters[0].children!;
                                } else {
                                  subOptions = selected[0].children!;
                                  if (index == "IB Chinese")
                                    filterIBChinese = selected[0];
                                }
                                // subOptions = subOptions
                                //   ..removeWhere(
                                //       (item) => item.label == 'Benchmark');

                                List<BookFilter> subIBOptions = [];
                                if (ibindex != '')
                                  subIBOptions = filterIBChinese.children!
                                      .where((item) => item.label == ibindex)
                                      .toList()[0]
                                      .children!;
                                String? initialProgramType =
                                    dto.programType?[0];
                                return Column(
                                  children: [
                                    DropdownButtonFormField(
                                      dropdownColor: Get.isDarkMode
                                          ? AppTheme.colors.darkTheme4
                                          : Colors.white,
                                      value: initialProgramType,
                                      key: programTypeKey,
                                      decoration: InputDecoration(
                                        labelText: 'Program Type'.tr,
                                        labelStyle: TextStyle(
                                            color: Get.isDarkMode
                                                ? Get.theme.primaryColorDark
                                                : Colors.blueGrey),
                                      ),
                                      validator: FormBuilderValidators.compose(
                                          [FormBuilderValidators.required()]),
                                      items: bookfilters
                                          .map(
                                            (folder) => DropdownMenuItem(
                                              value: folder.label,
                                              child: Text(
                                                '${folder.label}',
                                                //overflow: TextOverflow.fade,
                                                style: TextStyle(
                                                    color: Get.isDarkMode
                                                        ? Get.theme
                                                            .primaryColorDark
                                                        : Colors.blueGrey),
                                              ),
                                            ),
                                          )
                                          .toList(),
                                      onChanged: (value) {
                                        _handleOptions(value);
                                        // var selected = bookfilters
                                        //     .where((item) => item.label == value)
                                        //     .toList();
                                        // for (var i = 0;
                                        //     i < selected[0].children!.length;
                                        //     i++) {
                                        //   AppKeys.searchFormKeys[i].currentState!
                                        //       .reset();
                                        // }
                                        initialProgremType();
                                        for (var i = 0; i < 6; i++) {
                                          AppKeys
                                              .searchFormKeys[i].currentState!
                                              .reset();
                                        }
                                      },
                                    ),
                                    // for (var child in subOptions
                                    //     .children!) //final etSkillScore1Key = GlobalKey<FormFieldState>();
                                    //   DropdownButtonFormField(
                                    //     //value: null,
                                    //     //key: etSkillScore1Key,
                                    //     decoration: InputDecoration(
                                    //       labelText: '${child.label}',
                                    //     ),
                                    //     validator: FormBuilderValidators.compose([
                                    //       FormBuilderValidators.required(context)
                                    //     ]),
                                    //     items: child.children!
                                    //         .map((folder) => DropdownMenuItem(
                                    //               value: folder.label,
                                    //               child: Text('${folder.label}'),
                                    //             ))
                                    //         .toList(),
                                    //     onChanged: (value) {
                                    //       _handleSubOptions(child.label, value);
                                    //     },
                                    //   ),

                                    if (index != "IB Chinese")
                                      ...getOptions(context, subOptions,
                                          _handleSubOptions, dto)
                                    else
                                      // for IB type type dropdown
                                      DropdownButtonFormField(
                                        value: dto.textType?[0],
                                        key: ibTypeKey,
                                        decoration: InputDecoration(
                                          labelText: 'IB Chinese Type'.tr,
                                          labelStyle: TextStyle(
                                              color: Get.isDarkMode
                                                  ? Get.theme.primaryColorDark
                                                  : Colors.blueGrey),
                                        ),
                                        validator:
                                            FormBuilderValidators.compose([
                                          FormBuilderValidators.required()
                                        ]),
                                        items: subOptions
                                            .map((folder) => DropdownMenuItem(
                                                  value: folder.label,
                                                  child:
                                                      Text('${folder.label}'),
                                                ))
                                            .toList(),
                                        onChanged: (value) {
                                          _handleIBOptions(value);
                                          // var selected = bookfilters
                                          //     .where((item) => item.label == value)
                                          //     .toList();
                                          // for (var i = 0;
                                          //     i < selected[0].children!.length;
                                          //     i++) {
                                          //   AppKeys.searchFormKeys[i].currentState!
                                          //       .reset();
                                          // }
                                          initialIBProgremType();
                                          // for (var i = 0; i < 4; i++) {
                                          //   IBAppKeys
                                          //       .searchIBFormKeys[i].currentState!
                                          //       .reset();
                                          // }
                                        },
                                      ),
                                    if (subIBOptions.length > 0)
                                      ...getIBOptions(context, subIBOptions,
                                          _handleSubIBOptions, dto),

                                    Container(
                                      width: 210.0,
                                      height: 45.0,
                                      margin: EdgeInsets.only(top: 21.0),
                                      child: MaterialButton(
                                        color: Get.isDarkMode
                                            ? Colors.white
                                            : Get.theme.primaryColor,
                                        onPressed: () {
                                          Navigator.of(context).pop();
                                        },
                                        child: Text(
                                          'OK'.tr,
                                          style: TextStyle(
                                              fontSize: 18.0,
                                              color: Get.isDarkMode
                                                  ? Colors.black
                                                  : Get
                                                      .theme.primaryColorLight),
                                        ),
                                      ),
                                    ),
                                  ],
                                );
                              } else {
                                return Column();
                              }
                            }),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          )),
    );
  }
}

// for program type dropdown
List<Widget> getOptions(context, options, handleSubOptions, dto) {
  List<Widget> data = [];
  for (var i = 0; i < options.length; i++) {
    // Log.debug(options[i].label);
    // Log.debug(options[i].children[0].value);
    // set the inital search value
    dynamic initialVal;
    if (options[i].label == 'Proficiency Level') {
      initialVal = dto.proficiencyLevel?[0];
    } else if (options[i].label == 'Interest Level') {
      initialVal = dto.interestLevel?[0];
    } else if (options[i].label == 'Text Type') {
      initialVal = dto.textType?[0];
    } else if (options[i].label == 'Topics') {
      initialVal = dto.topics?[0];
    } else if (options[i].label == 'Series') {
      initialVal = dto.seriesId?[0];
    }
    if (initialVal != null) {
      data.add(
        DropdownButtonFormField(
          isExpanded: true,
          value: initialVal,
          key: AppKeys.searchFormKeys[i],
          decoration: InputDecoration(
            labelText: options[i].label,
          ),
          validator:
              FormBuilderValidators.compose([FormBuilderValidators.required()]),
          items: options[i]
              .children!
              .map(
                (folder) => DropdownMenuItem(
                  value: folder.value,
                  child: Text('${folder.label}'),
                ),
              )
              .cast<DropdownMenuItem<Object>>()
              .toList(),
          onChanged: (value) {
            handleSubOptions(options[i].label, value);
          },
        ),
      );
    } else {
      if (initialVal != null) {
        data.add(
          DropdownButtonFormField(
            isExpanded: true,
            key: AppKeys.searchFormKeys[i],
            decoration: InputDecoration(
              labelText: options[i].label,
            ),
            validator: FormBuilderValidators.compose(
                [FormBuilderValidators.required()]),
            items: options[i]
                .children!
                .map(
                  (folder) => DropdownMenuItem(
                    value: folder.value,
                    child: Text(
                      '${folder.label}',
                    ),
                  ),
                )
                .cast<DropdownMenuItem<Object>>()
                .toList(),
            onChanged: (value) {
              handleSubOptions(options[i].label, value);
            },
          ),
        );
      } else {
        data.add(
          DropdownButtonFormField(
            dropdownColor:
                Get.isDarkMode ? AppTheme.colors.darkTheme4 : Colors.white,
            isExpanded: true,
            key: AppKeys.searchFormKeys[i],
            decoration: InputDecoration(
              labelText: options[i].label,
              labelStyle: TextStyle(
                  color: Get.isDarkMode
                      ? Get.theme.primaryColorDark
                      : Colors.blueGrey),
            ),
            validator: FormBuilderValidators.compose(
                [FormBuilderValidators.required()]),
            items: options[i]
                .children!
                .map(
                  (folder) => DropdownMenuItem(
                    value: folder.value,
                    child: SingleChildScrollView(
                      scrollDirection: Axis.vertical,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '${folder.label}',
                            style: TextStyle(
                                color: Get.isDarkMode
                                    ? Get.theme.primaryColorDark
                                    : Colors.blueGrey),
                          ),
                          Divider(
                            color: Get.isDarkMode
                                ? Get.theme.primaryColor
                                : Colors.grey[100],
                          ),
                        ],
                      ),
                    ),
                  ),
                )
                .cast<DropdownMenuItem<Object>>()
                .toList(),
            onChanged: (value) {
              handleSubOptions(options[i].label, value);
            },
          ),
        );
      }
    }
  }
  return data;
}

// for IB type type dropdown
List<Widget> getIBOptions(context, options, handleSubIBOptions, dto) {
  List<Widget> data = [];
  for (var i = 0; i < options.length; i++) {
    //Log.debug(options[i].label);
    dynamic initialVal;
    if (options[i].label == 'Proficiency Level') {
      initialVal = dto.proficiencyLevel?[0];
    } else if (options[i].label == 'My Grade') {
      initialVal = dto.interestLevel?[0];
    } else if (options[i].label == 'Text Type') {
      initialVal = dto.textType?[0];
    } else if (options[i].label == 'Themes') {
      initialVal = dto.topics?[0];
    } else if (options[i].label == 'Mock Exams') {
      initialVal = dto.seriesId?[0];
    }
    data.add(
      DropdownButtonFormField(
        value: initialVal,
        // key: IBAppKeys.searchIBFormKeys[i],
        decoration: InputDecoration(
          labelText: options[i].label,
        ),
        validator:
            FormBuilderValidators.compose([FormBuilderValidators.required()]),
        items: options[i]
            .children!
            .map((folder) => DropdownMenuItem(
                  value: folder.value,
                  child: Text('${folder.label}'),
                ))
            .cast<DropdownMenuItem<Object>>()
            .toList(),
        onChanged: (value) {
          handleSubIBOptions(options[i].label, value);
        },
      ),
    );
  }
  return data;
}
